package vip.xiaonuo.message.impl;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;
import vip.xiaonuo.facedoor.modular.message.MessageSender;
import vip.xiaonuo.facedoor.modular.message.domain.Message;

import javax.annotation.Resource;


@Getter
@Slf4j
@Component
public class LocalMessageSender implements MessageSender {


    @Resource
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public String send(Message message) {
        MessageBuilder<String> messageBuilder = MessageBuilder.withPayload(message.getMsg());
        org.springframework.messaging.Message<String> msg = null;
        // 携带tag发送
        if (StringUtils.isNotBlank(message.getMsgKey())) {
            messageBuilder.setHeader("KEYS", message.getMsgKey());
        }

        // 非顺序消息携带tag发送
        if (StringUtils.isNotBlank(message.getTag()) && !message.isOrderly()) {
            msg = messageBuilder.build();
            rocketMQTemplate.syncSend(message.getTopic() + ":" + message.getTag(), msg);
        }

        // 非顺序消息不携带tag发送
        if (StringUtils.isBlank(message.getTag()) && !message.isOrderly()) {
            msg = messageBuilder.build();
            rocketMQTemplate.syncSend(message.getTopic(), msg);
        }

        // 顺序消息携带tag发送
        if (StringUtils.isNotBlank(message.getTag()) && message.isOrderly()) {
            msg = messageBuilder.build();
            rocketMQTemplate.syncSendOrderly(message.getTopic() + ":" + message.getTag(), msg, message.getShardingKey());
        }
        // 顺序消息不携带tag发送
        if (StringUtils.isNotBlank(message.getTag()) && message.isOrderly()) {
            msg = messageBuilder.build();
            rocketMQTemplate.syncSendOrderly(message.getTopic() + ":" + message.getTag(), msg, message.getShardingKey());
        }
        return msg.getHeaders().getId().toString();
    }


}
